package hbt.dao;

import hbt.HibernateUtil;

import java.util.List;

import model.Proveedor;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HibernateProveedorDAO {
	private static HibernateProveedorDAO instancia = null;
	private static SessionFactory sf = null;
	
	public static HibernateProveedorDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateProveedorDAO();
		} 
		return instancia;
	}
	
	public Proveedor levantarProveedor(String cuit) throws Exception{
		Session session = sf.openSession();
		Query query = session.createQuery("from Proveedor p where p.cuit = :cuit");
		query.setParameter("cuit", cuit);
		List<Proveedor>proveedors=query.list();
		return proveedors.get(0);
	}

	public boolean guardarProveedor(Proveedor p) {
		try {
			Session session = sf.openSession();
			session.beginTransaction();
			session.persist(p);
			session.flush();
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			e.printStackTrace();
			return false;
		}
		
	}

	public boolean actualizarProveedor(Proveedor proveedor) {
		try {
			Session session = sf.openSession();
			session.beginTransaction();
			session.saveOrUpdate(proveedor);
			session.flush();
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			e.printStackTrace();return false;
		}
	}

	public boolean borrarProveedor(Proveedor proveedor) {
		try {
			Session session = sf.openSession();
			String borrar = "DELETE FROM Proveedor p WHERE p.cuit = :cuit";
			Query query = session.createQuery(borrar);
			query.setParameter("cuit", proveedor.getCuit());
			query.executeUpdate();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
